// background.js
/* eslint-disable */
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: 'Save as Bookmark',
        title: '保存为书签',
        contexts: ['all']
    });
});
function printBookmark(bookmark) {
    console.log(`Title: ${bookmark.title}`);
    console.log(`URL: ${bookmark.url}`);
    console.log(`ID: ${bookmark.id}`);
    console.log(`Parent ID: ${bookmark.parentId}`);
    console.log(`Date added: ${new Date(bookmark.dateAdded).toString()}`);
}
// 监听右键菜单项的点击事件
chrome.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId === 'Save as Bookmark') {

      chrome.bookmarks.get(chrome.bookmarks.TREE_NODE, function(treeNodes) {
          treeNodes.forEach(function(node) {
              if (node.children) {
                  node.children.forEach(printBookmark);
              } else {
                  printBookmark(node);
              }
          });
      });
      chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
          var activeTab = tabs[0];
          if (activeTab) {
              let bookmark = {
                  id: Date.now(),
                  url: activeTab.url,
                  title: activeTab.title,
                  group:{
                      groupId: 0,
                      groupName: '未分组'
                  },
              }
              chrome.storage.local.get(['bookmarksGroup','bookmarksList'], (items) => {
                  let bookmarksGroup = items.bookmarksGroup || [{groupName: '未分组', groupId: 0}];
                  let bookmarksList = items.bookmarksList || [];
                  let isExist = bookmarksList.some((item) => {
                      if (item.url === bookmark.url) {
                          const matchingGroup = bookmarksGroup.find(itemG => itemG.groupId === item.group.groupId);
                          if (matchingGroup) {
                              mynotif('当前网页已收藏在：'+ matchingGroup.groupName)
                          }
                          return true;
                      }
                  });
                  if (!isExist) {
                      bookmarksList.push(bookmark)
                      chrome.storage.local.set({bookmarksList, bookmarksGroup}, () => {
                          mynotif('当前网页已收藏')

                      });
                  }

              });

          }
      })
  }
});
function mynotif(msg){
    if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
    } else {
        // 当数据加载完成后，再创建通知
        chrome.notifications.create({
            type: 'basic',
            iconUrl: '../img.png',
            title: '通知',
            message: msg
        });
    }
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === "saveBookmarkAction") {
        chrome.storage.local.get("bookmarks", function(items) {
            var bookmarks = items.bookmarks || {};
            if(request.bookmark.group === ""){
                request.bookmark.group = "默认分组";
            }
            if (!bookmarks[request.bookmark.group]) {
                bookmarks[request.bookmark.group] = [];
            }
            var bookmark = {
                name: request.bookmark.name,
                url: request.bookmark.url,
                id: Date.now()
            };
            bookmarks[request.bookmark.group].push(bookmark);
            const realBookmarks = Object.fromEntries(
                Object.entries(bookmarks).filter(([key, value]) => value.length > 0)
            );
            chrome.storage.local.set({ bookmarks: realBookmarks }, function() {
                console.log("Bookmarks saved");
            });
        });
    }
});
